package com.mingqijia.gassafety.shared.vcc;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * VCC授权配置
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年07月12日 15:45
 */
@Data
@Component
@ConfigurationProperties(prefix = "vcc.open-client")
@Slf4j
public class VccTokenClientConfig {
    @JsonIgnore
    private String server;
    private String grantType;
    private String openAppId;
    private String openAppSecret;


    private static final String TEMPLATE_TOKEN = "%s/open-auth/oauth2/token?%s";
    private static final String TEMPLATE_TOKEN_CHECK = "%s/open-auth/oauth2/token/check";
    private static final String TEMPLATE_REFRESH = "%s/open-auth/oauth2/token/refresh";

    public String getGenTokenUrl(String sign) {
        return String.format(TEMPLATE_TOKEN, server, sign);
    }

    public String getRefreshTokenUrl() {
        return String.format(TEMPLATE_REFRESH, server);
    }

    public String getCheckTokenUrl() {
        return String.format(TEMPLATE_TOKEN_CHECK, server);
    }

    public String toJson() {
        return JSONUtil.toJsonStr(this);
    }

    public String getToken() {
        String token = "";
        Map<String, Object> params = new HashMap<>();
        params.put("openAppId", openAppId);
        params.put("openAppSecret", openAppSecret);
        try {
            String body = com.mingqijia.gassafety.shared.utils.HttpUtil.getBody(com.alibaba.fastjson.JSONObject.toJSONString(params),
                    server + UrlConst.OPEN_TOKEN.getUrl(), "", "");
            if (StringUtils.isEmpty(body)) return null;
            log.info("getToken-response:{}", body);
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(body);
            if (Integer.parseInt(jsonObject.getString("code")) == 0) {
                com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");
                token = data.getString("token");
            }
        } catch (Exception e) {
            log.error("getToken-error:{}", e);
            return null;
        }
        return token;
    }
}


